package com.lzp.systemopt.messenger

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log

/**
 * @description:
 * @author: lxp
 * @date: 2022/3/17 下午4:17
 */
class MessengerService : Service() {
    companion object {
        const val MSG_ID = 0x110
        private const val TAG = "MessengerManager"
    }

    private val mMessenger = Messenger(object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msgfromClient: Message) {
            val msgToClient = Message.obtain(msgfromClient) //返回给客户端的消息
            when (msgfromClient.what) {
                MSG_ID -> {
                    msgToClient.what = MSG_ID
                    try {
                        val data = msgfromClient.data
                        val fromData = data.getString("data")
                        Log.d(TAG, "服务端》》》收到消息: $fromData")
                        //模拟耗时
                        //Thread.sleep(2000)
                        val bundle = Bundle()
                        bundle.putString("data", "收到消息：$fromData")
                        msgToClient.data = bundle
                        msgfromClient.replyTo.send(msgToClient)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    } catch (e: RemoteException) {
                        e.printStackTrace()
                    }
                }
            }
            super.handleMessage(msgfromClient)
        }
    })

    override fun onBind(intent: Intent?): IBinder? {
        return mMessenger.binder
    }
}